package cn.jilian.security.exception;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.jilian.common.domain.R;

@ControllerAdvice
public class AuthorizationExceptionHandler {

	@Autowired
	private ObjectMapper objectMapper;
	
	@ExceptionHandler({UnauthenticatedException.class,AuthenticationException.class })
    public String authenticationException(HttpServletRequest request, HttpServletResponse response) {
		String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)) {
        	writeJson(R.fail("当前会话已失效，请重新登录"),response);
            return null;
        } else {
            return "redirect:/login/index.html";
        }
    }
	 	@ExceptionHandler(AuthorizationException.class)
	 	Object handleException(AuthorizationException e,HttpServletRequest request){
	 		String requestType = request.getHeader("X-Requested-With");
	 		if("XMLHttpRequest".equals(requestType)){
	 		   return R.fail("没有访问权限");
	 		}else{
	 			ModelAndView modelAndView = new ModelAndView();
		        modelAndView.setViewName("auz_error");
		        modelAndView.addObject("code", e.getMessage());
		        modelAndView.addObject("msg", e.getMessage());
		        return modelAndView;
	 		}
	 		
	    }
	 	
	 	private void writeJson(Object map, HttpServletResponse response) {
	        PrintWriter out = null;
	        try {
	            response.setCharacterEncoding("UTF-8");
	            response.setContentType("application/json; charset=utf-8");
	            out = response.getWriter();
	            out.write(objectMapper.writeValueAsString(map));
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            if (out != null) {
	                out.close();
	            }
	        }
	    }
}
